package com.cc.wechat.utils;

import com.cc.wechat.common.ResultCode;
import com.cc.wechat.exception.BusinessException;
import com.cc.wechat.common.constants.MessageConstants;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 文件验证工具类
 */
public class FileValidationUtils {

    // 允许的文件类型
    private static final Set<String> ALLOWED_IMAGE_TYPES = new HashSet<>(Arrays.asList(
            "image/jpeg",
            "image/png",
            "image/gif"
    ));

    // 最大文件大小（10MB）
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    /**
     * 验证文件
     *
     * @param file 文件对象
     * @param type 文件类型（avatar/image等）
     * @throws BusinessException 当文件验证失败时抛出
     */
    public static void validateFile(MultipartFile file, String type) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, MessageConstants.File.FILE_EMPTY);
        }

        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new BusinessException(ResultCode.FILE_SIZE_EXCEEDED, 
                String.format(MessageConstants.File.FILE_TOO_LARGE, MAX_FILE_SIZE / 1024 / 1024));
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !ALLOWED_IMAGE_TYPES.contains(contentType.toLowerCase())) {
            throw new BusinessException(ResultCode.FILE_TYPE_NOT_ALLOWED, 
                String.format(MessageConstants.File.INVALID_FILE_TYPE, String.join(", ", ALLOWED_IMAGE_TYPES)));
        }

        // 检查文件名
        String filename = file.getOriginalFilename();
        if (filename == null || filename.trim().isEmpty()) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, MessageConstants.File.INVALID_FILENAME);
        }
    }
} 